<template>
  <Dialog v-model="dialogVisible" :title="formData.isFolder?'新建文件夹':'重命名'" >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="名称" prop="title">
        <el-input v-model="formData.title" placeholder="请输入名称" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import * as FileApi from '@/api/infra/file'

defineOptions({ name: 'CreateFolderForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  id: undefined,
  title: '',
  isFolder: 1,
  parentId: 0,
})

const formRules = reactive({
  title: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (id: number | any,parentId:number | any,isFolder: number) => {
  resetForm()
  dialogVisible.value = true
  formData.value.parentId = parentId
  if (id) {
    const res = await FileApi.getDetail(id)
    formData.value = res.data
  }else{
    formData.value.isFolder = isFolder
    formData.value.id = id
  }
  
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

/** 提交表单 */
const submitForm = () => {
  // 校验表单
  formRef.value.validate()
  formLoading.value = true

  if (formData.value.id) {
    FileApi.updateDetail(formData.value)
    message.success(t('common.updateSuccess'))
  } else {
    FileApi.createFile(formData.value)
    message.success(t('common.createSuccess'))
  }

  dialogVisible.value = false
  formLoading.value = false
  // 发送操作成功的事件
  emit('success')
}

/** 重置表单 */
const resetForm = () => {
  // 重置上传状态和文件
  formLoading.value = false
  formData.value = {
    id: undefined,
    title: '',
    isFolder: 1,
    parentId: 0,
  }
  formRef.value?.resetFields()
}
</script>